use std::{net::{IpAddr, Ipv4Addr}, ops::Deref, path::{Path, PathBuf}};

use rocket::{config::LogLevel, form::name::Name, fs::NamedFile, http::{self, hyper::{body::HttpBody, server::conn::Http},  Status}, response::{content::RawJson, Responder}, route, serde::{json::{self, Json}, Serialize}, time::macros, tokio::{fs::File, io::AsyncReadExt}};
use rocket::serde::*;

#[macro_use] extern crate rocket;

#[derive(Default)]
#[derive(Debug)]
#[derive(Deserialize)]
#[serde(crate = "rocket::serde")]
struct Mssg {
    name:String,
    ff:String,
}

#[get("/<v_name>")]
fn getf(v_name:&str) -> String{
    let s1 = String::from("new msg get: ");
    let s1 = s1 + v_name;
    s1
}

#[get("/ckplayer/<path..>")]
async fn ckplayerfn(path:PathBuf) -> Option<NamedFile>{
    // println!("{}",path.to_str().unwrap());
    NamedFile::open(Path::new("./res/ckplayer/").join(path)).await.ok()
}

#[get("/")]
async fn defaultf() -> Option<NamedFile>{
    NamedFile::open("./res/index.html").await.ok()
}

#[get("/png")]
async fn pngf() -> Option<NamedFile>{
    NamedFile::open("./res/landscape.webp").await.ok()
}

#[get("/file")]
async fn sendf() -> File{
    let f = File::open("./res/landscape.webp").await.unwrap();
    f
}

#[post("/postt",data = "<mssg>")]
fn postt(mssg:Json<Mssg>) -> String{
    format!("{:?}",mssg)
}

#[get("/<video_name>")]
async fn getvi(video_name :&str) -> Option<NamedFile>{
    let name:Vec<&str> = video_name.split(".").collect();
    if name.len() > 1 && name[1] == "ts"{
        return NamedFile::open(String::from("./v/") + video_name).await.ok()
    }else {
        let uri = String::from("./v/") + video_name + ".m3u8";
        let f = NamedFile::open(uri).await.ok();
        f
    }
}

#[launch]
fn rocket() -> _ {
    let port = std::env::var("PORT").unwrap();
    let mut cfig = rocket::Config::release_default();
    cfig.address = IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0));
    cfig.port = port.parse().unwrap();
    cfig.log_level = LogLevel::Normal;
    rocket::build().mount("/", routes![getf]).configure(&cfig)
    .mount("/", routes![defaultf])
    .mount("/", routes![pngf])
    .mount("/", routes![sendf,postt,ckplayerfn])
    .mount("/v", routes![getvi])
}
